package com.zxshhy.controller;

import com.alibaba.fastjson.JSONObject;
import com.zxshhy.entity.Order;
import com.zxshhy.service.OrderService;
import com.zxshhy.vo.OrderVo;
import com.zxshhy.vo.ResultVo;
import com.zxshhy.zookeeper.ZKClientBase;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zxs
 */
@RefreshScope
@RestController
@RequestMapping("/zk")
@Slf4j
public class OrderZookeeperController {

    @Resource
    private ZKClientBase zkClientBase;

    /**
     * zookeeper
     * @param orderVo
     * @return
     */
    @PostMapping("/createNode")
    public ResultVo createNode(@RequestBody OrderVo orderVo){
        log.info("zookeeper创建节点：{}", orderVo);
        ZkClient zkClient = zkClientBase.init();
        zkClient.createPersistent("/zxshhy/zkclient",true);
        zkClient.writeData("/zxshhy","zxshhy");
        System.out.println("/zxshhy value is " + zkClient.readData("/zxshhy"));
        zkClient.createPersistent("/zxshhy/zkclient!c1");
        zkClient.createPersistent("/zxshhy/zkclient/c2");
        List<String> children = zkClient.getChildren("/zxshhy/zkclient");
        for(String str : children){
            System.out.println("获取到zookeeper节点信息：" + str);
        }
        System.out.println("size :  "+ zkClient.countChildren("/zxshhy/zkclient"));
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //递归删除
        zkClient.deleteRecursive("/zxshhy");
        return ResultVo.ok().put("order",zkClient.getChildren("/zookeeper"));
    }

}
